<script setup lang="ts">
import ReCol from "@/components/ReCol";
import { ref, computed } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage } from "element-plus";

const props = withDefaults(defineProps<{
  taskData: {
    id: number;
    task_type?: {
      name: string;
      feedback_type: string | string[];
    };
    taskType?: {
      name: string;
      feedback_type: string | string[];
    };
    customer?: {
      fullname: string;
    };
    remark: string;
    deadline_at: number;
  };
  viewCustomerDetail?: (customer: any) => void;
}>(), {
  taskData: () => ({
    id: 0,
    task_type: {
      name: "",
      feedback_type: "text"
    },
    customer: {
      fullname: ""
    },
    remark: "",
    deadline_at: 0
  })
});

const ruleFormRef = ref();
const formData = ref({
  feedback_text: "",
  feedback_images: [] as File[]
});

const imagePreviewUrls = ref<string[]>([]);
const uploadingCount = ref(0);

// 获取任务类型（兼容 task_type 和 taskType 两种格式）
const taskType = computed(() => {
  return props.taskData.task_type || props.taskData.taskType;
});

// 解析反馈类型
const feedbackTypes = computed(() => {
  if (!taskType.value?.feedback_type) return ["text"];
  
  const feedbackType = taskType.value.feedback_type;
  let parsedTypes: string | string[] = feedbackType;
  
  if (typeof feedbackType === "string") {
    try {
      // 尝试解析JSON格式
      parsedTypes = JSON.parse(feedbackType);
    } catch {
      // 如果不是JSON，按逗号分割
      parsedTypes = feedbackType.split(",");
    }
  } else if (Array.isArray(feedbackType)) {
    parsedTypes = feedbackType;
  }
  
  const result = Array.isArray(parsedTypes) ? parsedTypes : [parsedTypes];
  return result;
});

const needsText = computed(() => feedbackTypes.value.includes("text"));
const needsImage = computed(() => feedbackTypes.value.includes("image"));

// 检查是否为超时完成
const isOvertime = computed(() => {
  const now = new Date().getTime();
  const deadline = new Date(props.taskData.deadline_at * 1000).getTime();
  return now > deadline;
});

function getRef() {
  return ruleFormRef.value;
}

function getFormData() {
  return {
    ...formData.value,
    status: isOvertime.value ? 2 : 1 // 超时完成:2, 正常完成:1
  };
}

function handleImagesChange(fileList: any[]) {
  if (!fileList || fileList.length === 0) return;
  
  // 提取新添加的文件（Element Plus 上传组件格式）
  const newFiles = fileList
    .filter(item => item.raw && !formData.value.feedback_images.includes(item.raw))
    .map(item => item.raw);
    
  if (newFiles.length === 0) return;
  
  const maxImages = 5; // 最多5张图片
  
  if (formData.value.feedback_images.length + newFiles.length > maxImages) {
    ElMessage.warning(`最多只能上传${maxImages}张图片`);
    return;
  }
  
  // 添加新文件
  formData.value.feedback_images.push(...newFiles);
  
  // 生成预览URL
  newFiles.forEach(file => {
    imagePreviewUrls.value.push(URL.createObjectURL(file));
  });
}

function removeImage(index: number) {
  // 释放预览URL
  if (imagePreviewUrls.value[index]) {
    URL.revokeObjectURL(imagePreviewUrls.value[index]);
  }
  
  // 删除文件和预览URL
  formData.value.feedback_images.splice(index, 1);
  imagePreviewUrls.value.splice(index, 1);
}

defineExpose({ getRef, getFormData });

// 表单验证规则
const formRules = {
  feedback_text: [
    { 
      required: needsText.value && !needsImage.value, 
      message: "请填写反馈内容", 
      trigger: "blur" 
    }
  ]
};

// 验证图片是否上传（当需要图片反馈时）
const hasRequiredImages = computed(() => {
  if (!needsImage.value) return true;
  return formData.value.feedback_images.length > 0;
});
</script>

<template>
  <div class="task-complete-form">
    <!-- 任务信息展示 -->
    <div class="task-info">
      <div class="info-header">
        <h4>{{ taskType?.name || "任务详情" }}</h4>
        <el-tag 
          v-if="isOvertime" 
          type="warning" 
          size="small"
        >
          已超时
        </el-tag>
        <el-tag 
          v-else 
          type="success" 
          size="small"
        >
          正常完成
        </el-tag>
      </div>
      
      <div class="info-content">
        <div class="info-item">
          <span class="label">客户：</span>
          <span class="value">{{ taskData.customer?.fullname || "-" }}  
            <el-button type="primary" size="small" style="margin-left: 20px; height: 20px;" @click="viewCustomerDetail(taskData)">查看</el-button>
          </span>
        </div>

        <div class="info-item">
          <span class="label">任务描述：</span>
          <span class="value">{{ taskData.task_type.content || "-" }}</span>
        </div>
      </div>
    </div>

    <el-divider />

    <!-- 反馈表单 -->
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="formRules"
      label-width="90px"
      label-position="top"
    >
      <el-row :gutter="20">
        <!-- 文本反馈 -->
        <re-col v-if="needsText" :value="24" :xs="24" :sm="24">
          <el-form-item 
            :label="needsImage ? '文字反馈' : '反馈内容'" 
            prop="feedback_text"
          >
            <el-input
              v-model="formData.feedback_text"
              type="textarea"
              :rows="needsImage ? 3 : 4"
              :placeholder="needsImage ? '可选的文字说明...' : '请详细描述任务完成情况...'"
              style="width: 100%"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </re-col>

        <!-- 图片反馈 -->
        <re-col v-if="needsImage" :value="24" :xs="24" :sm="24">
          <el-form-item label="图片反馈">
            <!-- 图片预览网格 -->
            <div v-if="formData.feedback_images.length > 0" class="images-preview">
              <div class="images-grid">
                <div 
                  v-for="(url, index) in imagePreviewUrls" 
                  :key="index"
                  class="image-item"
                >
                  <img :src="url" alt="预览图片" class="preview-image" />
                  <div class="image-actions">
                    <el-button 
                      type="danger" 
                      size="small" 
                      :icon="useRenderIcon('ep:delete')" 
                      @click="removeImage(index)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
                
                <!-- 继续添加图片 -->
                <div v-if="formData.feedback_images.length < 5" class="add-more-container">
                  <el-upload
                    class="add-more-upload"
                    :show-file-list="false"
                    :multiple="true"
                    :auto-upload="false"
                    accept="image/*"
                    :on-change="(file, fileList) => handleImagesChange(fileList)"
                  >
                    <div class="add-more-btn">
                      <el-icon><i-ep-plus /></el-icon>
                      <div class="add-text">添加图片</div>
                    </div>
                  </el-upload>
                </div>
              </div>
            </div>
            
            <!-- 初次上传区域 -->
            <el-upload
              v-else
              class="upload-demo"
              drag
              :show-file-list="false"
              :multiple="true"
              :auto-upload="false"
              accept="image/*"
              :on-change="(file, fileList) => handleImagesChange(fileList)"
            >
              <el-icon class="el-icon--upload">
                <i-ep-upload-filled />
              </el-icon>
              <div class="el-upload__text">
                将图片拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持jpg/png格式，最多5张图片，单个文件不超过10MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </re-col>
      </el-row>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.task-complete-form {
  padding: 0;
  
  .task-info {
    margin-bottom: 16px;
    
    .info-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      
      h4 {
        margin: 0;
        font-size: 14px;
        font-weight: 600;
      }
    }
    
    .info-content {
      background: #f8f9fa;
      border-radius: 6px;
      padding: 12px;
      
      .info-item {
        display: flex;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          min-width: 70px;
          color: #606266;
          font-weight: 500;
        }
        
        .value {
          color: #303133;
          flex: 1;
          word-break: break-all;
        }
      }
    }
  }
  
  :deep(.el-divider) {
    margin: 16px 0;
  }
  
  :deep(.el-form-item__label) {
    color: #606266;
    font-weight: 500;
  }
  
  :deep(.el-upload) {
    width: 100%;
  }
  
  :deep(.el-upload-dragger) {
    width: 100%;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.2s ease;
    
    &:hover {
      border-color: #409eff;
    }
  }
  
  :deep(.el-icon--upload) {
    font-size: 28px;
    color: #8c939d;
    margin: 40px 0 16px;
  }
  
  :deep(.el-upload__text) {
    color: #606266;
    font-size: 14px;
    text-align: center;
    
    em {
      color: #409eff;
      font-style: normal;
    }
  }
  
  :deep(.el-upload__tip) {
    font-size: 12px;
    color: #909399;
    margin-top: 7px;
  }
  
  .images-preview {
    margin-bottom: 16px;
    
    .images-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
      gap: 12px;
      max-width: 100%;
      
      @media (max-width: 768px) {
        grid-template-columns: repeat(3, 1fr);
      }
    }
    
    .image-item {
      position: relative;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      overflow: hidden;
      background: #fff;
      aspect-ratio: 1;
      
      .preview-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
      }
      
      .image-actions {
        position: absolute;
        top: 4px;
        right: 4px;
        display: flex;
        gap: 4px;
        opacity: 0;
        transition: opacity 0.2s ease;
        
        .el-button {
          padding: 4px 8px;
          font-size: 12px;
        }
      }
      
      &:hover .image-actions {
        opacity: 1;
      }
    }
    
    .add-more-container {
      display: flex;
      align-items: center;
      justify-content: center;
      aspect-ratio: 1;
      
      .add-more-upload {
        width: 100%;
        height: 100%;
        
        :deep(.el-upload) {
          width: 100%;
          height: 100%;
        }
      }
      
      .add-more-btn {
        width: 100%;
        height: 100%;
        border: 2px dashed #d9d9d9;
        border-radius: 6px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: border-color 0.2s ease;
        background: #fafafa;
        
        &:hover {
          border-color: #409eff;
          background: #f0f9ff;
        }
        
        .el-icon {
          font-size: 20px;
          color: #8c939d;
          margin-bottom: 4px;
        }
        
        .add-text {
          font-size: 12px;
          color: #606266;
        }
      }
    }
  }
}
</style> 